import java.util.List;

/**
 * Created by cjz on 2018/8/2.
 */
public class DriveLink {


    Link link;
    List<Link> preLinks;
    List<Link> nextLinks;

    LinkFinishListener linkFinishListener;

    public DriveLink(Link link, LinkFinishListener linkFinishListener) {
        this.link = link;

        preLinks = Utils.getLinkTargetIs(link.source);
        List<Link> brother = Utils.getLinkTargetIs(link.target);
        brother.remove(link);
        preLinks.addAll(brother);
        nextLinks = Utils.getLinkSourceIs(link.target);

        this.linkFinishListener = linkFinishListener;
    }

    public synchronized void runIt(Main main, boolean ignoreBrother) {

        boolean canRun = true;

        if (!"0".equals(link.source) && !ignoreBrother) {
            for (Link preLink : preLinks) {
                System.out.println("Thread"+Thread.currentThread().getId()+":"+"------run " + link + " check " + preLink + ",is " + preLink.isFinished);
                canRun = canRun && preLink.isFinished;
            }

        }

        if (canRun) {


            //TODO: run node...

            link.isFinished = true;
            if (ignoreBrother) {
                List<Link> brotherNode = Utils.getLinkTargetIs(link.target);
                System.out.println( "Thread"+Thread.currentThread().getId()+":"+ link+" 's all brother's father is ok , then change brother state to true");
                for (Link oneNode : brotherNode) {
                    oneNode.isFinished = true;
                }
            }
            linkFinishListener.onLinkFinish(link, nextLinks);

        } else {
            System.out.println("Thread"+Thread.currentThread().getId()+":"+"------ADD to wait: " + link);
            main.addToWatch(link);
        }
    }

    public interface LinkFinishListener {
        void onLinkFinish(Link currentLink, List<Link> nextLinks);
    }

}
